package stru1.day7;

import java.util.StringJoiner;

/**
 * 203. 移除链表元素
 */
public class Solution3 {
    public static void main(String[] args) {
        ListNode head1 = new ListNode(1, new ListNode(2, new ListNode(3)));
        print(removeElements(head1, 3));

        ListNode head2 = new ListNode(3, new ListNode(3, new ListNode(3)));
        print(removeElements(head2, 3));
    }

    /**
     * 迭代，构建next为头节点的源节点，使其可以遍历且可删除所有节点
     */
    public static ListNode removeElements(ListNode head, int val) {
        ListNode ans = new ListNode(0, head);
        ListNode temp = ans;
        while (temp.next != null) {
            if (temp.next.val == val) temp.next = temp.next.next;
            else temp = temp.next;
        }
        return ans.next;
    }

    private static void print(ListNode list) {
        StringJoiner sj = new StringJoiner(",", "[", "]");
        while (list != null) {
            sj.add(String.valueOf(list.val));
            list = list.next;
        }
        System.out.println(sj);
    }
}
